const express = require('express') // 项目服务端使用express框架
const app = express()
const path = require('path')
const fs = require('fs')

//使用nodejs自带的http、https模块
const http = require('http')
const https = require('https')
const { default: axios } = require('axios')

//根据项目的路径导入生成的证书文件
const privateKey = fs.readFileSync(
  path.join(__dirname, './private.pem'),
  'utf8'
)
const certificate = fs.readFileSync(path.join(__dirname, './file.crt'), 'utf8')
const credentials = { key: privateKey, cert: certificate }

const httpServer = http.createServer(app)
const httpsServer = https.createServer(credentials, app)

//可以分别设置http、https的访问端口号
const PORT = 8000
const SSLPORT = 8001

//创建http服务器
httpServer.listen(PORT, function () {
  console.log('HTTP Server is running on: http://localhost:%s', PORT)
})

//创建https服务器
httpsServer.listen(SSLPORT, function () {
  console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT)
})

//可以根据请求判断是http还是https
app.get('/test', async function (req, res) {
  if (req.protocol === 'https') {
    // const result = await axios.get('http://localhost:3000/')
    // console.log(result.data)
    // res.status(200)
    // res.json(result.data)
    res.status(200).send('This is https visit!')
  } else {
    res.status(200).send('This is http visit!')
  }
})

// 静态资源目录
app.use(express.static(path.join(__dirname, 'public')))
